<?php
namespace app\index\controller;


class Index
{
    public function getXl()
    {
        set_time_limit(0);
//        $article_url = 'http://weibo.com/p/aj/v6/mblog/mbloglist?domain=100605&id=1006051230663070&page=2&pre_page=4';
//        $article_url = 'http://weibo.com/p/aj/v6/mblog/mbloglist?domain=100605&page=1&pagebar=2&id=1006051230663070&pre_page=1';

//        $article_url = 'http://weibo.com/p/aj/v6/mblog/mbloglist?ajwvr=6&domain=100605&is_search=0&visible=0&is_all=1&is_tag=0&profile_ftype=1&page=2&pagebar=0&id=1006051230663070&pre_page=2';
        //http://weibo.com/p/aj/v6/mblog/mbloglist?ajwvr=6&domain=100605&c=spr_qdhz_bd_baidusmt_weibo_s&nick=鹿晗&is_all=1&pagebar=0&pl_name=Pl_Official_MyProfileFeed__25&id=1006051230663070&script_uri=/tangyan&feed_type=0&page=1&pre_page=1&domain_op=100605&__rnd=1499669328428   喜比利时王室
//echo urldecode($article_url);die;
        $header = [
            'Cookie:SINAGLOBAL=5001536749429.547.1484810341157; SCF=Ar1l4YeFDLNjNvxTrME01BCUfom4dee8pTP9wXmyG7B7dN4i86FHU057zbXi4-7mMU_HnbBAbMO4ctyqR4KbuKw.; SUHB=0mxVsrm96YRR6y; ALF=1523325271; SUB=_2AkMvrMbFf8NxqwJRmP4RzmjibYRyyg_EieKZ8DceJRMxHRl-yT83qkwGtRCkCNCtbcnLTLskyUyJ1oeByHFlbw..; SUBP=0033WrSXqPxfM72-Ws9jqgMF55529P9D9WWzlmfvy_ZaG5ugKeIaOzx0; YF-V5-G0=b59b0905807453afddda0b34765f9151; login_sid_t=4d72d0dbf462e62ce82edb1b7edb5dd3; YF-Ugrow-G0=ad06784f6deda07eea88e095402e4243; WBStorage=28a7a732670d7678|undefined; YF-Page-G0=3d55e26bde550ac7b0d32a2ad7d6fa53; _s_tentry=www.baidu.com; Apache=589884674388.1082.1499669213096; ULV=1499669213116:23:3:1:589884674388.1082.1499669213096:1499234907620; UOR=,,www.baidu.com',
        ];
//        $str = get_page($article_url, $header);
//        $str = json_decode($str, true);
//        dump($str);die;
        $i = 1;
        $p = 1;
        while (1) {
            switch ($i) {
                case 1:
                    $article_url = "http://weibo.com/p/aj/v6/mblog/mbloglist?domain=100605&page={$p}&pagebar=0&id=1006051230663070&pre_page=".($p-1);
                    break;
                case 2:
                    $article_url = "http://weibo.com/p/aj/v6/mblog/mbloglist?domain=100605&page={$p}&pagebar=0&id=1006051230663070&pre_page={$p}";
                    break;
                case 3:
                    $article_url = "http://weibo.com/p/aj/v6/mblog/mbloglist?domain=100605&page={$p}&pagebar=1&id=1006051230663070&pre_page={$p}";
                    break;
                default:
                    $i=1;$p++;continue;
            }
            $str = get_page($article_url, $header);
            if (!preg_match('/WB_feed_detail/is', $str)) {
                break;
            }
            $str = json_decode($str, true);
            preg_match_all('/feed_list_item[^>]+>\s*<div[^>]+WB_feed_detail.+?feed_list_repeat/is', $str['data'], $list);

            $insert = [];
            $s = time();
            foreach ($list[0] as $v) {
                if (preg_match('/feed_list_forwardContent/is', $v)) {
                    //转发
                    preg_match('/WB_info.+?<div[^>]+WB_from.+?title="([^"]+).+?<div[^>]+>(.+?)<\/div\s*>.+?<div[^>]+feed_list_forwardContent(.+?)WB_feed_handle.+?forward_btn_text.+?<em\s*>\s*(\d+).+?comment_btn_text.+?<em\s*>\s*(\d+).+?like_status.+?<em\s*>\s*(\d+)/is', $v, $arr);
                    preg_match('/WB_info.+?usercard="[^"]*id=(\d+)[^>]+>([^<]+).+?WB_text[^>]+>\s*(.+?)<\/div.+?ficon_forward.+?<em\s*>\s*(\d+).+?ficon_repeat.+?<em\s*>\s*(\d+).+?ficon_praised.+?<em\s*>\s*(\d+).+?WB_from.+?title="([^"]+)/is', $arr[3], $indirect);
                    $arr = [
                        'type' => 'indirect',
                        'pub_time' => strtotime($arr[1]),
                        'content' => trim($arr[2]),
                        'indirect' => $arr[4],
                        'comment' => $arr[5],
                        'praise' => $arr[6],
                        'inderect_account' => $indirect[1],
                        'inderect_title' => trim($indirect[2]),
                        'inderect_content' => trim($indirect[3]),
                        'indirect_pub_time' => strtotime($indirect[7]),
                        'indirect_indirect' => $indirect[4],
                        'indirect_comment' => $indirect[5],
                        'indirect_praise' => $indirect[6],
                    ];
                } else if (preg_match('/<!--\s*图片个数/is', $v)) {
                    //直发
                    preg_match('/WB_info.+?<div[^>]+WB_from.+?title="([^"]+).+?<div[^>]+>(.+?)<\/div.+?WB_media_wrap.+?ul(.+?)ul.+?WB_feed_handle.+?forward_btn_text.+?<em\s*>\s*(\d+).+?comment_btn_text.+?<em\s*>\s*(\d+).+?like_status.+?<em\s*>\s*(\d+)/is', $v, $arr);
                    preg_match_all('/src="([^"]+)/is', $arr[3], $imgs);
                    $arr = [
                        'type' => 'direct',
                        'pub_time' => strtotime($arr[1]),
                        'content' => trim($arr[2]),
                        'indirect' => $arr[4],
                        'comment' => $arr[5],
                        'praise' => $arr[6],
                        'imgs' => json_encode($imgs[1])
                    ];
                } else {
                    //话题
                    preg_match('/WB_info.+?<div[^>]+WB_from.+?title="([^"]+).+?<div[^>]+>(.+?)<\/div\s*>.+?WB_feed_handle.+?forward_btn_text.+?<em\s*>\s*(\d+).+?comment_btn_text.+?<em\s*>\s*(\d+).+?like_status.+?<em\s*>\s*(\d+)/is', $v, $arr);
                    $arr = [
                        'type' => 'direct',
                        'pub_time' => strtotime($arr[1]),
                        'content' => trim($arr[2]),
                        'indirect' => $arr[3],
                        'comment' => $arr[4],
                        'praise' => $arr[5],
                    ];
                }
                $insert[] = $arr;
            }
            if (!empty($insert)) {
                M('MediaBlogRecord')->addAll($insert);
            }
            $i++;
            if ($i == 4) {
                $p++;
                $i = 1;
            }
        }
        echo 'success';
    }

    public function index()
    {
//        $article_url = 'http://mp.weixin.qq.com/profile?src=3&timestamp=1490320289&ver=1&signature=mRUtkUSD6JoL9Q7BjFM4u92aiXzK2xtmJ7YF5kcno19vLyQbG1KOz8CCGIUJxNsxC0bOFy4MqFj312BSkZFqmA==';
//        $article_url = 'https://mp.weixin.qq.com/mp/profile_ext?action=getmsg&__biz=MTgwNTE3Mjg2MA==&f=json&frommsgid=1000000576&count=10&scene=124&is_ok=1&uin=MzQ5MDU3NDA2OQ%3D%3D&key=32ff7e6b073562f9e201fdb57b62ceddfda803cb498352d4f2c141b293c02f6b15f4019c15fd4f0858a09f90150e91ea1c187370b52a372518feb1bc8b1dc2b6723a733147bc3066c9af515b029d3e02&pass_ticket=6sfk%2BKxXJ591G5fTyHcyqNODlpyEJsiPSJ%2BBXhEJcMpuiFjyFvfScQRoL8LbQvvT&wxtoken=&x5=0&f=json HTTP/1.1';

        //http://mp.weixin.qq.com/s/M21-TEsykAGbwouRTNoYJA


        //通过weixin.sougou.com 抓取公众号文章  START
//        $datas = [];
//        $wx_data = $this->get_article_list_by_sougou_weixin($datas, 'lengtoo652');
//
//        dump($datas);die;
        //通过weixin.sougou.com 抓取公众号文章   END
//        die;

        //根据微信公众号历史消息抓取文章
        set_time_limit(0);
        $datas = [];
        $header = [
            'cookie : wxtokenkey=3f361f2662a2750db52dc29ee49f50f6f369d0b29b2456e2c8e57890025a42e9; wxticket=1128909091; wxticketkey=48ad826eb601b5cac2c70326548045e0f369d0b29b2456e2c8e57890025a42e9; wap_sid=CPXdt4ANEkByUG9JUlpJcllPbVlGSGJiUFJCS1FiM3dxRWJNbHpoSnRQak4yV0wxSUpodGhBUl94RW1xdEQ3X1hLQ1FfMmNMGAQgpBQowOGBmgswoZ/TxgU=; wap_sid2=CPXdt4ANElwzWW9sZHhjYkNKWEdtR1NjVDU4NzZSVWRlREVxY3lKdGo4TFU3RTZFemJkU1FWWGtaMXpQMHFjZVY2b3NBRE1sTXhNaUtKZDF4U21qQWxiYmlvT3cwb0VEQUFBfg==',
        ];
        $option = [
            'msgid' => '9999999999',
            'biz' => 'MzIxNjUyOTM4MQ==',
        ];
        $this->get_article_list_by_wx_history($datas, $header, $option);
        dump($datas);

    }

    /**
     * 根据搜狗微信抓取文章
     * @notice 注意这个方法只能抓取最近10次发文
     * @param $datas
     * @param $wx_username
     * @return array|bool
     */
    public function get_article_list_by_sougou_weixin(&$datas, $wx_username)
    {
        $str = get_page('http://weixin.sogou.com/weixin?query=' . $wx_username);
//        echo $str;die;

        preg_match('/(<a[^>]+account_image.+?<\/a\s*>).+?>\s*'.$wx_username.'\s*<.+?微信扫一扫关注.+?<img[^>]+src\s*=\s*[\'|"]([^\'|"]+).+?介绍.+?<dd[^>]*>([^<]+)(.+?认证.+?<dd[^>]*>([^<]+))?/is', $str, $c);
//        dump($c);die;
        if (empty($c[0])) {
            return false;
        }
        preg_match('/<a[^>]+href\s*=\s*[\'|"]([^\'|"]+)/is', $c[1], $article_list_url);
        preg_match('/<img[^>]+src\s*=\s*[\'|"]([^\'|"]+)/is', $c[1], $logo_url);

        $wx_data = [
            'qrcode_url' => trim($c[2]), //二维码图片路径
            'intro' => trim($c[3]), //功能介绍
            'authentication' => isset($c[5]) ? trim($c[5]) : '', //功能介绍
            'logo_url' => trim($logo_url[1]),
        ];

        $str = file_get_contents(html_entity_decode(trim($article_list_url[1])));
        preg_match('/msgList\s*=\s*(\{.+?\});/is', $str, $list_json);
//        echo $list_json[1];
        $list = json_decode($list_json[1], true);
        $this->package_data($datas, $list['list']);
        return $wx_data;
    }

    /**
     * 根据微信公众号历史消息抓取文章 没抓一页停两秒
     * @notice 注意这个方法需要手动设置cookie才能抓取
     * @param array $datas
     * @param string $msgid
     * @return bool
     */
    public function get_article_list_by_wx_history(array &$datas, array $header, array $option) {
        $article_url = 'https://mp.weixin.qq.com/mp/profile_ext?action=getmsg&__biz='.$option['biz'].'&f=json&frommsgid='.$option['msgid'].'&count=10';

        $str = get_page($article_url, $header);
//        echo $str;die;
        $json = json_decode($str, true);
//        dump($json);
        $list = json_decode($json['general_msg_list'], true);
//        dump($list);echo '-----------------------------------<br>';die;
        if (empty($list['list']) || count($datas) > 100) {
            return false;
        }

        /*
        "list": [ //最外层的键名；只出现一次，所有内容都被它包含。
            {//这个大阔号之内是一条多图文或单图文消息，通俗的说就是一天的群发都在这里
                "app_msg_ext_info":{//图文消息的扩展信息
                    "content_url": "图文消息的链接地址",
                    "cover": "封面图片",
                    "digest": "摘要",
                    "is_multi": "是否多图文，值为1和0",
                    "multi_app_msg_item_list": [//这里面包含的是从第二条开始的图文消息，如果is_multi=0，这里将为空
                        {
                            "content_url": "图文消息的链接地址",
                            "cover": "封面图片",
                            "digest": ""摘要"",
                            "source_url": "阅读原文的地址",
                            "title": "子内容标题"
                        },
                        ...//循环被省略
                    ],
                    "source_url": "阅读原文的地址",
                    "title": "头条标题"
                },
                "comm_msg_info":{//图文消息的基本信息
                    "datetime": '发布时间，值为unix时间戳',
                    "type": 49 //类型为49的时候是图文消息
                }
            },
            ...//循环被省略
        ]
        */

        $v = $this->package_data($datas, $list['list']);
        sleep(2);
        $option['msgid'] = $v['comm_msg_info']['id'];
        $this->get_article_list_by_wx_history($datas, $header, $option);
    }

    public function package_data(&$datas, $list)
    {
        foreach ($list as $v) {

            if (empty($v['app_msg_ext_info'])) {
                continue;
            }

            $datas[] = [
                'msgid' => $v['comm_msg_info']['id'],
                'pubtime' => $v['comm_msg_info']['datetime'], //发布时间
                'eq' => '0', //第几篇
                'title' => $v['app_msg_ext_info']['title'], //标题
                'digest' => $v['app_msg_ext_info']['digest'], //描述
                'content_url' => $v['app_msg_ext_info']['content_url'], //文章链接
                'headImg_url' => $v['app_msg_ext_info']['cover'], //头图
            ];

            //多图文
            if ($v['app_msg_ext_info']['is_multi'] == 0 || empty($v['app_msg_ext_info']['multi_app_msg_item_list'])) {
                continue;
            }
            foreach ($v['app_msg_ext_info']['multi_app_msg_item_list'] as $key=>$val) {
                $datas[] = [
                    'msgid' => $v['comm_msg_info']['id'],
                    'pubtime' => $v['comm_msg_info']['datetime'],
                    'eq' => $key+1,
                    'title' => $val['title'],
                    'digest' => $val['digest'],
                    'content_url' => $val['content_url'],
                    'headImg_url' => $val['cover'],
                ];
            }
        }
        return $v;
    }

    public function get_wx_info($article_url)
    {
        $qrcode_url = str_replace('https://mp.weixin.qq.com/s?', "https://mp.weixin.qq.com/mp/qrcode?scene=10000004&", $article_url);
        //获取点赞数和阅读数
        $article_data_request_url = str_replace('http://mp.weixin.qq.com/s', 'http://mp.weixin.qq.com/mp/getcomment', $article_url);
        $article_data = json_decode(file_get_contents($article_data_request_url), true);
        $read_num = $article_data['read_num']; //阅读数
        $like_num = $article_data['like_num']; //点赞数

        $str = _https_post($article_url);

        //公众号微信账号
        preg_match('/微信号.+?profile_meta_value[^>]+>([^<]+)/is', $str, $username);
        preg_match('/var\s+nickname\s*=\s*["|\']([^"|\']+)/is', $str, $nickname);
        //发布时间（时间戳）
        preg_match('/var\s+ct\s*=\s*["|\'](\d+)/is', $str, $pubtime);
        //图片路径
        $name = createOrderNo('WX');
        $dirname = sprintf('./wx_img/%s/%s/%s/%s/', date('Y'), date('m'), date('d'), $name);
        createDir($dirname);

        //保存公众号二维码图片
        file_put_contents($dirname . 'qrcode.jpg', file_get_contents($qrcode_url));

        //匹配正文
        preg_match('/(<h2[^>]+rich_media_title[^>]+>([^<]+).+?(<div[^>]+rich_media_content.+?))<script/is',$str, $content);

        $title = trim($content[2]); //微信文章标题
        $content = preg_replace('/\s{2,}/is', ' ', $content[1]); //微信文章正文

        //图片存入本地
        preg_match_all('/<img[^>]+data-type[^\w]+(\w+)[^>]+>/is', $content, $imgs_type);
        preg_match_all('/<img[^>]+data-src[^\w]+([^"|\']+)[^>]+>/is', $content, $imgs_src);
        if (!empty($imgs_type[1])) {
            foreach ($imgs_src[1] as $k => $v) {
                $imgName = $dirname . $k . '.' . $imgs_type[1][$k];
                file_put_contents($imgName, file_get_contents($v));
                $content = str_replace($imgs_type[0][$k], "<img src='$imgName' />", $content);
            }
        }

        $data = [
            'read_num' => $read_num,
            'like_num' => $like_num,
            'content' => $content,
            'title' => $title,
            'img_dir' => $dirname, //图片本地路径
            'pubtime' => $pubtime[1],
            'username' => trim($username[1]),
            'nickname' => trim($nickname[1]),
        ];
        return $data;
    }

    public function test()
    {
        pdf('<h1>dsadsadsa</h1>');die;
        $model = model('User');
        $data = $model->select();
        dump($data);

        //引用第三方库
        vendor('tcpdf.tcpdf');
        $n = new \Tcpdf();
    }

    public function wximg()
    {
        header('Content-type: image/jpg');
        $str = _https_post('http://mmbiz.qpic.cn/mmbiz_jpg/GsuL1FRLKd0v16OYNasI3QX9fmib2ria0gF56IuFGfeyKtMBKvrwFOnhhZwdLymsMJ2t2q3GbHemmLzyzJTUC5dw/0?wx_fmt=jpeg');
        file_put_contents('./1.jpeg', $str);
        echo $str;die;
    }

}
